package com.learing.note.studythread;

import javax.sound.midi.Soundbank;
import java.util.concurrent.*;

/**
 * @description: TODO
 * @author: 唐晓军
 * @date: 2021/10/30 13:49
 * @version: 1.0.0
 * @company: 北京凤凰学易科技有限公司
 **/
public class TestPC {
    public static void main(String[] args) {
        // 生产者生产鸡  放到容器  消费者从容器中取
        SynContainer synContainer = new SynContainer();
        new Productor(synContainer).start();
        new Consumer(synContainer).start();
    }
}

//产品
class Chicken {
    public int id;
    public Chicken(int id) {
        this.id = id;
    }
}

//容器
class SynContainer {
    //定义一个容器
    Chicken[] chickens = new Chicken[10];
    //容器计数器
    int count = 0;

    //添加鸡到容器
    public synchronized void push(Chicken chicken) throws InterruptedException {
        //如果容器满了，就需要等待消费者消息
        if (count == chickens.length) {
            //通知消费消费者消费，生产等待
            this.wait();
        }
        //如果没有满，我们就要生产
        chickens[count] = chicken;
        count++;
        //可以通知消费者消费
        this.notifyAll();
    }

    //消费者吃鸡
    public synchronized Chicken pop() throws InterruptedException {
        if (count == 0) {
            //等待生产者生产，消费者等待
            this.wait();
        }
        count--;
        Chicken chicken = chickens[count];
        this.notifyAll();
        return chicken;
    }
}

//生产者
class Productor extends Thread {
    private SynContainer synContainer;

    public Productor(SynContainer synContainer) {
        this.synContainer = synContainer;
    }

    @Override
    public void run() {
        for (int i = 1; i <= 100; i++) {
            Chicken chicken = new Chicken(i);
            try {
                synContainer.push(chicken);
                System.out.println("生产第" + i + "只鸡");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

//顾客
class Consumer extends Thread {
    private SynContainer synContainer;

    public Consumer(SynContainer synContainer) {
        this.synContainer = synContainer;
    }

    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            try {
                System.out.println("顾客吃" + synContainer.pop().id + "鸡");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
